﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ThoughtWorks.QRCode;
using ThoughtWorks.QRCode.Codec;
using System.Drawing;
using System.Text;
using WeChat.Common;
using BLL;
using System.Data;
using System.Threading;

namespace WeChat.UserInfo
{
    public partial class Qrcode : System.Web.UI.Page
    {
        public string head_img = String.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            string openid = "";
            string rfkh =String.Empty;
          
           GetUserInfoBLL gu = new GetUserInfoBLL();
            if (!IsPostBack)
            {
                //认证后得到code值
                if (Request.QueryString["code"] != null || Request.QueryString["code"] != "")
                {
                    string code = Request.QueryString["code"];
                    ApplicationLog.Write("code:" + code);
                    if (Session["openid"] == null || Session["openid"].ToString() == "")
                    {
                        Session["openid"] = OAuthHelper.getOpenid(code);
                    }
                    // openid = "opc0cwJ1_dCnJRnrcmTNaMXGyPBo";
                    openid = Session["openid"].ToString();

                    ApplicationLog.Write("获取到的openid:" + openid);
                    // 验证是否绑定账号,未绑定则跳转提示绑定账号
                    if (!new BindIdBLL().verifyId(openid))
                    {
                        Response.Redirect("/Binding.aspx?openid=" + openid);
                    }
                }
                DataSet ds = gu.getUserInfo(openid);
                var rybh = ds.Tables[0].Rows[0]["rybh"].ToString();
                 head_img = ds.Tables[0].Rows[0]["images"].ToString()=="" ? "../images/head.jpg" : ds.Tables[0].Rows[0]["images"].ToString();
                var rfye = ds.Tables[0].Rows[0]["rfye"].ToString();
                var ryxm = ds.Tables[0].Rows[0]["ryxm"].ToString();
                 rfkh = ds.Tables[0].Rows[0]["rfkh"].ToString();
                accounts.Text = float.Parse(rfye).ToString() + "元";
                uname.Text = ryxm;
                cardnum.Text = rybh;
                //string monData = string.Format("{0:X}", Convert.ToInt64(rfkh));
                //if (monData.Length > 8)
                //{
                //    monData = monData.Substring(monData.Length - 8);
                //}
                //else
                //{
                //    monData = monData.PadLeft(10, '0');
                //}
                //rfkh = monData;

                //卡号转换规则：
                //从数据库取到卡号后，先转16进制，得到16进制卡号后不足8位，
                //左端用0补齐，然后按字节高低位转换位置即可
                rfkh = Convert.ToString(Convert.ToInt64(rfkh), 16);
                rfkh = rfkh.PadLeft(8, '0');//左端用0补齐8位                
                rfkh = rfkh.Substring(6, 2) + rfkh.Substring(4, 2) + rfkh.Substring(2, 2) + rfkh.Substring(0, 2);

                string Start = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).AddMinutes(-5).ToString("yyyy-MM-dd HH:mm:ss");
                Start = Start.Replace(" ", "");
                Start = Start.Replace("-", "");
                Start = Start.Replace(":", "");
                Start = Start.Replace("/", "");
                string End = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).AddMinutes(5).ToString("yyyy-MM-dd HH:mm:ss");
                End = End.Replace(" ", "");
                End = End.Replace("-", "");
                End = End.Replace(":", "");
                End = End.Replace("/", "");
                ThoughtWorksQRCode(rfkh + Start + End + CRC.CRC.ToModbusCRC16(rfkh + Start + End, true), rfkh);


            }




        }
        private void ThoughtWorksQRCode(string strtxt,string rfkh)
        {
            try
            {
                Bitmap bt;
                string enCodeString = strtxt;
                QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
                bt = qrCodeEncoder.Encode(enCodeString, Encoding.UTF8);
                string filename = DateTime.Now.ToString(rfkh+"yyyymmddhhmmss");
                filename = filename.Replace(" ", "");
                filename = filename.Replace(":", "");
                filename = filename.Replace("-", "");
                filename = filename.Replace(".", "");
                bt.Save(Server.MapPath("~/images/") + filename + ".jpg");
                this.Image1.ImageUrl = "~/images/" + filename + ".jpg";
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        //public void GenerateQRCode(string content)
        //{
        //    try
        //    {
        //       // _fileLog.Info("GenerateQRCode|开始生成二维码");
        //        if (null != content)
        //        {
        //            //初始化二维码生成工具
        //            var qrCodeEncoder = new QRCodeEncoder
        //            {
        //                QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,
        //                QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M,
        //                QRCodeVersion = 0,
        //                QRCodeScale = 4
        //            };
        //            //将字符串生成二维码图片
        //            var image = qrCodeEncoder.Encode(content);
        //            var ms = new MemoryStream();
        //            image.Save(ms, ImageFormat.Png);
        //            Response.BinaryWrite(ms.GetBuffer());
        //            Response.End();
        //        }
        //        //_fileLog.Info("CloudCardController|GenerateQRCode|成功生成二维码");
        //    }
        //    catch (Exception ex)
        //    {
        //        //_fileLog.Error("GenerateQRCode|生成二维码出现异常,异常信息：" + ex.Message);
        //    }

        //}
        //private void CreateCode_Simple(string nr)
        //{
        //    QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
        //    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
        //    qrCodeEncoder.QRCodeScale = 4;
        //    qrCodeEncoder.QRCodeVersion = 8;
        //    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
        //    //System.Drawing.Image image = qrCodeEncoder.Encode("4408810820 深圳－广州 小江");
        //    System.Drawing.Image image = qrCodeEncoder.Encode(nr);
        //    string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg";
        //    string filepath = Server.MapPath(@"~\Upload") + "\\" + filename;
        //    System.IO.FileStream fs = new System.IO.FileStream(filepath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
        //    image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);

        //    fs.Close();
        //    image.Dispose();
        //    //二维码解码
        //    var codeDecoder = CodeDecoder(filepath);
        //}

        ///// <summary>
        ///// 二维码解码
        ///// </summary>
        ///// <param name="filePath">图片路径</param>
        ///// <returns></returns>
        //public string CodeDecoder(string filePath)
        //{
        //    if (!System.IO.File.Exists(filePath))
        //        return null;
        //    Bitmap myBitmap = new Bitmap(Image.FromFile(filePath));
        //    QRCodeDecoder decoder = new QRCodeDecoder();
        //    string decodedString = decoder.decode(new QRCodeBitmapImage(myBitmap));
        //    return decodedString;
        //}

    }
}